package org.learn.spring5.dao.impl;

import org.learn.spring5.entiy.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao {

    //注入JdbcTemplate對象
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void add(User user) {
        //1.創建sql語句
        String sql = "insert into t_user values(?,?,?)";
        //2.調用方法实现
        Object[] args = {user.getId(), user.getUserName(), user.getStatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    public int update(User user) {
        String sql = "update t_user set user_name =?,status=? where id =?";
        Object[] args = {user.getUserName(), user.getStatus(), user.getId()};
        int update = jdbcTemplate.update(sql, args);

        return update;
    }

    public int del(Integer id) {
        String sql = "delete from t_user where id =?";
        int update = jdbcTemplate.update(sql, id);
        return update;
    }

    public int queryCount() {
        String sql = "select count(*) from t_user";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    public User findOne(Integer id) {
        String sql = "select * from t_user where id =?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        return user;
    }

    public List<User> findAll() {
        String sql ="select * from t_user";
        List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    public void batchAdd(List<Object[]> users) {
        String sql = "insert into t_user values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        System.out.println(Arrays.asList(ints).toString());

    }

    public void batchUpdate(List<Object[]> users) {
        String sql = "update t_user set user_name =?,status=? where id =?";
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        System.out.println(Arrays.asList(ints).toString());

    }

    public void batchDel(List<Object[]> users) {
        String sql = "delete from t_user where id =?";
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        System.out.println(ints);
    }
}
